package cn.edu.lingnan.demo.controller;

import cn.edu.lingnan.demo.entity.Admin;
import cn.edu.lingnan.demo.entity.AdminQuery;
import cn.edu.lingnan.demo.entity.Student;
import cn.edu.lingnan.demo.entity.common.CommonResult;
import cn.edu.lingnan.demo.listener.StudentExcelListener;
import cn.edu.lingnan.demo.service.AdminService;
import cn.edu.lingnan.demo.service.StudentService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * (Admin)表控制层
 *
 * @author makejava
 * @since 2020-05-26 08:33:28
 */
//在使用模板页面的时候，不要使用@RestController，如果某些方法需要返回json格式，则在方法上使用@RestBody
//@RestController
@Controller
@RequestMapping("admin")
public class AdminController {
    /**
     * 服务对象
     */
    @Resource//@Autowired注入（注册组件）
    private AdminService adminService;

    @Autowired
    private StudentService studentService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    @ResponseBody
    public Admin selectOne(Integer id) {
        return this.adminService.queryById(id);
    }
    @GetMapping("select")
    @ResponseBody
    public Admin select() {
        return this.adminService.queryById(1);
    }

    /**
     * 前往登录页面
     *
     * @return 登录页面
     */
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    /**
     * 登录
     *
     * @param account 账号
     * @param password 密码
     * @param model 页面（数据）回显
     * @return 页面
     */
    @PostMapping("login")
    public String login(String account, String password, Model model){
        Admin admin = this.adminService.login(account, password);
        if (admin == null){
            //登录失败
            model.addAttribute("msg", "账号密码错误！");
            return "login";
        }
//        使用cookie记住密码；
//        将账号信息存到session
        return  "index";
    }

    /**
     * 前往主页面
     *
     * @return 主页面
     */
    @RequestMapping("toIndex")
    public String toIndex() {
        return "index";
    }

    /**
     * 插入
     *
     * @return json格式数据
     */
    @PostMapping("insert")
    @ResponseBody
    public Admin insert(Admin admin){
        return adminService.insert(admin);
    }

    /**
     * 前往欢迎页面（在主页中）
     *
     * @return 欢迎页面
     */
    @RequestMapping("toWelcome")
    public String toWelcome(){
        return "welcome";
    }

    /**
     * 查询全部信息
     *
     * @return 全部信息
     */
//    @PostMapping("queryAll")
//    @ResponseBody
//    public Object qurryAll(Admin bean){
//        //CommonResult类是为了拼成table.json中的数据类型一致
//        CommonResult<Admin> result = new CommonResult<>();
//        List<Admin> admins = adminService.queryAll(bean);
//        result.setCode(0);
//        result.setCount(admins.size());
//        result.setData(admins);
//        return result;
//    }

    @PostMapping("queryAll")
    @ResponseBody
    public Object queryAll(Integer page, Integer limit, AdminQuery bean){
        System.out.println("bean==" + bean);
        //CommonResult类是为了拼成table.json中的数据类型一致
        CommonResult<Admin> result = new CommonResult<>();
        IPage<Admin> iPage = adminService.queryAllByLimit(page, limit, bean);
        result.setCode(0);
        result.setCount(iPage.getTotal());
        result.setData(iPage.getRecords());
        System.out.println();
        return result;
    }

    @RequestMapping("toList")
    public String toList() {
        return "user/admin_list";
    }

    @RequestMapping("toAdd")
    public String toAdd(Model model) {
        model.addAttribute("bean", new Admin());
        return "user/admin_add";
    }

    @PostMapping("save")
    @ResponseBody
    public Object save(Admin bean){
        Boolean result = false;
//        判断添加还是修改
//        通过判断账号是否存在
        if (bean.getId() != null){
            //编辑
            result = adminService.update(bean) > 0;
        }else {
            //添加
            bean.setRegDate(new Date());
            result = adminService.insert(bean).getId() != null;
        }
        return result;
    }

    @RequestMapping("toEdit")
    public String toEdit(Integer id, Model model){
        System.out.println("id==" + id);

        Admin bean = adminService.queryById(id);
        model.addAttribute("bean", bean);
        return "user/admin_add";
    }

    @PostMapping("deleteById")
    @ResponseBody
    public boolean deleteById(Integer[] ids) {
        if (ids == null || ids.length == 0) {
            return false;
        }
        adminService.deleteById(Arrays.asList(ids));
        return true;
    }

    /**
    *   文件上传
    *@param
    *@return
    */
    @PostMapping("upload")
    @ResponseBody
    public Object upload(MultipartFile file) {
        CommonResult<String> result = new CommonResult<>();
        try {
            EasyExcel.read(file.getInputStream(), Student.class,
                    new StudentExcelListener(studentService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            result.setMsg("Excel上传出错");
        }
        result.setData(file.getOriginalFilename());
        return result;
    }
}